package com.java.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.java.domain.*;
import com.java.service.OrderService;
import com.java.service.PayInfoAllService;
import com.java.service.ShopCartService;
import com.java.service.impl.OrderServiceImpl;
import com.java.service.impl.PayInfoAllServiceImpl;
import com.java.service.impl.ShopCartServiceImpl;
import com.java.utils.AlipayConfig;
import com.java.utils.DateUtils;
import com.java.utils.IdWorker;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

/**
 * @version 2020.3.4
 * @User 悠恋
 * @Data 2022/11/26
 * @Time 19:51
 */
@WebServlet("/order/*")
public class OrderServlet extends BaseServlet {
    private OrderService orderService = new OrderServiceImpl();
    private ShopCartService shopCartService = new ShopCartServiceImpl();
    private PayInfoAllService payInfoAllService = new PayInfoAllServiceImpl();
    private OrderDetail orderDetail = null;
    // 工具获取id
    private IdWorker idWorker = new IdWorker();
    String oid = "";
    Double total = 0.0;// 获取商品总价

    // 添加订单（直接购买）
    public void addOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        total = 0.0;
        ShopCart shopCart = new ShopCart();

        // 接收前端传过来的数据
        BeanUtils.populate(shopCart, request.getParameterMap());
        //System.out.println(shopCart.getKucun());
        //System.out.println(shopCart);
        // 订单编号
        oid = idWorker.nextId() + "";
        // 取出当前登录用户的所有信息
        Users users = (Users) request.getSession().getAttribute("user");
        String uname = users.getuName();

        // 添加订单详情  将当前购买的信息添加到集合中
        List<OrderDetail> shopCarts = new ArrayList<>();
        orderDetail = new OrderDetail();
        orderDetail.setOdid(idWorker.nextId() + "");
        orderDetail.setGname(shopCart.getGname());
        orderDetail.setGprice(shopCart.getGprice() + 0.0);
        total = shopCart.getGtotal() + 0.0;
        orderDetail.setGtotal(total);
        orderDetail.setNum(shopCart.getGnum());
        orderDetail.setGimg(shopCart.getGimg());
        orderDetail.setOid(oid);
        //System.out.println(orderDetail);
        shopCarts.add(orderDetail);
        // 添加订单
        Order order = new Order(oid, shopCart.getGtotal() + "", "已支付", DateUtils.getDateFormart(), uname);
        //System.out.println(order);
        // 调用添加方法
        Boolean aBoolean = orderService.addOrder(order, shopCarts);
        // 调用更新库存的方法
        orderService.updateInventory(shopCart.getGid(),shopCart.getKucun()-shopCart.getGnum());

        if (aBoolean) System.out.println("添加成功！");
        else System.out.println("添加失败！");
        pay(response);
    }

    // 添加订单
    public void addOrders(HttpServletRequest request, HttpServletResponse response) throws Exception {
        total = 0.0;
        // 获取所有被支付的商品id
        String checkeds = request.getParameter("checkedsId");

        String[] split = checkeds.split(",");
        // 订单编号
        oid = idWorker.nextId() + "";
        // 取出当前登录用户的所有信息
        Users users = (Users) request.getSession().getAttribute("user");
        String uname = users.getuName();
        //System.out.println(uname);
        // 获取购物车中所有的商品
        List<ShopCart> shopCartLists = (List<ShopCart>) request.getSession().getAttribute("shopCartList");
        List<OrderDetail> shopCarts = new ArrayList<>();
        for (String value : split) {
            for (ShopCart shopCart : shopCartLists) {
                if (shopCart.getUname().equals(uname) && Integer.parseInt(value) == shopCart.getGid()) {
                    total = total + shopCart.getGtotal();
                    //System.out.println(total);
                    orderDetail = new OrderDetail();
                    orderDetail.setOdid(idWorker.nextId() + "");
                    orderDetail.setGname(shopCart.getGname());
                    orderDetail.setGprice(shopCart.getGprice() + 0.0);
                    orderDetail.setGtotal(shopCart.getGtotal() + 0.0);
                    orderDetail.setNum(shopCart.getGnum());
                    orderDetail.setGimg(shopCart.getGimg());
                    orderDetail.setOid(oid);
                    shopCarts.add(orderDetail);
                    // 更新库存
                    orderService.updateInventory(shopCart.getGid(),shopCart.getKucun()-shopCart.getGnum());
                }
            }
        }
        // 调用添加订单
        Order order = new Order(oid, total + "", "已支付", DateUtils.getDateFormart(), uname);

        Boolean aBoolean = orderService.addOrder(order, shopCarts);

        // 调用业务 删除购物车内已经购买的商品
        //System.out.println("更新前:" + shopCartLists);
        List<ShopCart> shopCartList = shopCartService.delAll(split, uname);
        //System.out.println("删除成功之后："+shopCartList);
        // 更新session
        request.getSession().setAttribute("shopCartList", shopCartList);
        //System.out.println("更新后："+request.getSession().getAttribute("shopCartList"));
        if (aBoolean) System.out.println("添加成功！");
        else System.out.println("添加失败！");
        pay(response);


    }

    public void pay(HttpServletResponse response) throws Exception {

        //设置响应编码格式--------防止中文产生乱码
        response.setContentType("text/html;charset=utf-8");
        //产生输出流
        PrintWriter out = response.getWriter();

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = oid;
        //付款金额，必填
        String total_amount = total + "";
        //订单名称，必填
        String subject = "订单" + oid;
        //商品描述，可空
        String body = "我是健豪他大爹！！！";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        out.println(result);
    }

    //回调，接收支付宝付款后的参数
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }


        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //支付宝交易号
        String trade_no = request.getParameter("trade_no");
        //付款金额
        double total_amount = Double.parseDouble(request.getParameter("total_amount"));
        PayInfoAll payInfoAll = new PayInfoAll();
        payInfoAll.setPorder(out_trade_no);
        payInfoAll.setPordername(trade_no);
        payInfoAll.setPtotal(total_amount);

        payInfoAllService.savePayInfo(payInfoAll);
        // 转发页面
        response.sendRedirect("../goods/query");

    }
}
